<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\FamilyTree;
use app\common\model\Room;
use app\common\model\RoomApply;
use app\common\model\RoomUser;
use think\Db;
use think\Exception;

class Clan extends Api{
    //protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 创建家族验证
     * @return bool
     * @throws \think\Exception
     */
    public function check($check_type){
        $count = RoomUser::where('user_id',$this->auth->id)->where('types',2)->count();
        if($count > 0){
            $this->error('您已存在家族，无法操作');
        }
        $familyCount = FamilyTree::where('user_id',$this->auth->id)->where('family_id',$this->auth->id)->count();
        if($familyCount < 1){
            $this->error('对不起,您不是家庭树家长,无法创建');
        }

        if($check_type == 1 || $check_type == 3){
            $num = Config::getValue('num','clan');
            $fCount = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->count();
            if($fCount < $num){
                $this->error('对不起,您不是家庭树家长或者你的家庭树成员没有达到创建家族得人数，无法创建');
            }
        }
        if($check_type == 3 || $check_type == 4){
            return true;
        }
        $this->success('验证成功');
    }

    public function create(){
        $this->check(3);
        $name = request()->post('name');
        $avatar = request()->post('avatar');
        if(empty($name) || empty($avatar)){
            $this->error('参数错误');
        }
        Db::startTrans();
        try{
            // 在世男
            $aliveMaleCount = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->where('status',1)->where('gender',1)->count();
            // 在世女
            $aliveWomanCount = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->where('status',1)->where('gender',0)->count();
            // 去世男
            $dieMaleCount = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->where('status',0)->where('gender',1)->count();
            // 去世女
            $dieWomanCount = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->where('status',0)->where('gender',0)->count();
            $room = Room::create([
                'name'              => $name,
                'image'             => $avatar,
                'user_id'           => $this->auth->id,
                'pid'               => RoomUser::where('user_id',$this->auth->id)->where('types',1)->value('room_id'),
                'user_count'        => $aliveMaleCount + $aliveWomanCount + $dieMaleCount + $dieWomanCount,
                'alive_male_count'  => $aliveMaleCount,
                'alive_woman_count' => $aliveWomanCount,
                'die_male_count'    => $dieMaleCount,
                'die_woman_count'   => $dieWomanCount,
                'seniority'         => implode(',',FamilyTree::getSeniority($this->auth->id)),
                'types'             => 2,
            ]);
            $ids = FamilyTree::where('family_id',$this->auth->id)->where('user_id','<>',0)->column('user_id');
            $data = [];
            foreach($ids as $v){
                $data[] = [
                    'user_id'=> $v,
                    'room_id'=> $room['id'],
                    'types'  => 2,
                ];
            }
            (new RoomUser())->saveAll($data);
            // 修改等级
            \app\common\model\User::where('id',$this->auth->id)->update(['level'=>1]);
            Db::commit();
            $this->success('创建成功');
        }catch(Exception $e){
            Db::rollback();
            write_log($e->getMessage(),'创建家族错误');
            $this->error('创建失败,请联系管理员');
        }
    }

    /**
     * 申请加入家族
     */
    public function apply(){
        $this->check(4);
        $roomId = request()->post('room_id');
        $roomInfo = Room::where('id',$roomId)->where('types',2)->field('id,user_id')->find();
        if(empty($roomInfo)){
            $this->error('参数错误');
        }
        $count = RoomApply::where('room_id',$roomInfo['id'])->where('apply_user_id',$this->auth->id)->where('status','IN',[0,1])->count();
        if($count > 0){
            $this->error('申请已存在!');
        }
        RoomApply::create([
            'room_id'       => $roomInfo['id'],
            'apply_user_id' => $this->auth->id
        ]);

        $this->success('申请成功,等待族长审核!');
    }


    /**
     * 家族申请列表
     */
    public function applyList(){
        $roomUser = RoomUser::where('user_id',$this->auth->id)->where('types',2)->find();
        if(empty($roomUser)){
            $this->error('不是族长无法查看!');
        }
        $room = Room::where('id',$roomUser['room_id'])->field('id,user_id')->find();
        if(empty($room) || $room['user_id'] != $this->auth->id){
            $this->error('不是族长无法查看!');
        }
        $list = RoomApply::with('user')->where('room_id',$room['id'])->order('created_at','desc')->select();
        $this->success('获取成功',$list);
    }

    /**
     * 审核
     */
    public function examine(){
        $type = request()->post('type',1);// 类型:1=通过,2=拒绝
        $applyId = request()->post('apply_id'); // 审核id
        if(empty($applyId)){
            $this->error('参数错误');
        }
        if(!in_array($type,[1,2])){
            $this->error('审核类型错误');
        }

        $applyInfo = RoomApply::where('id',$applyId)->where('status',0)->find();
        if(empty($applyInfo)){
            $this->error('申请不存在');
        }
        $room = Room::where('id',$applyInfo['room_id'])->field('id,user_id')->find();
        if(empty($room) || $room['user_id'] != $this->auth->id){
            $this->error('不是族长无法操作!');
        }
        Db::startTrans();
        try{
            if($type == 1){
                $userIds = FamilyTree::where('family_id',$applyInfo['apply_user_id'])->where('user_id','>',0)->column('user_id');
                if(empty($userIds)){
                    throw new Exception('家庭不存在真实用户');
                }
                // 删除原家族数据
                RoomUser::where('user_id','IN',$userIds)->where('types',2)->delete();

                $createData = [];
                foreach($userIds as $v){
                    $createData[] = [
                        'room_id'   => $applyInfo['room_id'],
                        'user_id'   => $v,
                        'types'     => 2
                    ];
                }
                if(!empty($createData)){
                    (new RoomUser())->saveAll($createData);
                }
            }
            RoomApply::where('id',$applyId)->update(['status'=>$type]);

            Db::commit();
            $this->success('审核成功');
        }catch(Exception $e){
            Db::rollback();
            write_log($e->getMessage(),'家族审核错误');
            $this->error('审核失败,请联系管理员');
        }
    }

    /**
     * 禁言
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function prohibit(){
        $userId = request()->post('user_id');
        $status = request()->post('status',0);
        if(empty($userId) || !in_array($status,[0,1])){
            $this->error('参数错误');
        }
        $roomId = Room::where('user_id',$this->auth->id)->where('types',2)->value('id');
        if(empty($roomId)){
            $this->error('家族不存在');
        }
        $roomUserInfo = RoomUser::where('user_id',$userId)->where('room_id',$roomId)->find();
        if(empty($roomUserInfo)){
            $this->error('家族成员不存在');
        }
        RoomUser::where('id',$roomUserInfo['id'])->update(['status'=>$status]);
        $this->success('修改成功');
    }
}